import { createRouter, createWebHashHistory } from 'vue-router';
import keepAliveExclude from '@/reactive/index.js';

const routes = [
  { path: '/', component: () => import('@/views/home/index.vue') },
  {
    path: '/design',
    component: () => import('@/views/design/index.vue'),
    redirect: '/design/tab1',
    children: [
      {
        path: 'tab1',
        component: () => import('@/views/design/tab1/index.vue'),
        meta: {
          componentName: 'Tab1',
        },
        redirect: '/design/tab1/L1',
        children: [
          {
            path: 'L1',
            component: () => import('@/views/design/tab1/L1/index.vue'),
            meta: {
              componentName: 'Tab1,L1',
            },
          },
          {
            path: 'L2',
            component: () => import('@/views/design/tab1/L2/index.vue'),
            meta: {
              componentName: 'Tab1,L2',
            },
          },
          {
            path: 'L3',
            component: () => import('@/views/design/tab1/L3/index.vue'),
            meta: {
              componentName: 'Tab1,L3',
            },
          },
        ],
      },
      {
        path: 'tab2',
        component: () => import('@/views/design/tab2/index.vue'),
        meta: {
          componentName: 'Tab2',
        },
      },
      {
        path: 'tab3',
        component: () => import('@/views/design/tab3/index.vue'),
        meta: {
          componentName: 'Tab3',
        },
      },
    ],
  },
  {
    path: '/component',
    component: () => import('@/views/component/index.vue'),
    redirect: '/component/overview',
    children: [
      {
        path: 'overview',
        component: () => import('@/views/component/overview/index.vue'),
      },
      {
        path: 'button',
        component: () => import('@/views/component/button/index.vue'),
      },
    ],
  },
  {
    path: '/tab',
    component: () => import('@/views/component/tab/index.vue'),
  },
  {
    path: '/:pathMath(.*)*', // 匹配任意路由
    redirect: '/',
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

let oldHistoryPosition = 0;
router.beforeEach((to, from) => {
  const historyPosition = window.history.state.position || 0;
  if (historyPosition >= oldHistoryPosition) {
    // 前进时，window.history.state.position 这时还是旧值
    console.log('前进');
    keepAliveExclude.value = to.meta.componentName; // 取消组件缓存
  } else {
    // 后退时，window.history.state.position 这时已经是新值
    console.log('后退');
    keepAliveExclude.value = from.meta.componentName; // 取消组件缓存
  }
});

router.afterEach(() => {
  oldHistoryPosition = window.history.state.position || 0;
});

export default router;
